<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Visual Basic data types</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Visual Basic, learn Visubal Basic, data types, tutorial, programming language">
<meta name="description" content="This part of the Visual Basic tutorial covers Visual Basic data types.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Visual Basic data types</h1>

<p>
In this part of the Visual Basic tutorial, we will talk about data types. 
</p>

<p>
Computer programs work with data. Spreadsheets, text editors, calculators or chat clients.
Tools to work with various data types are essential part of a modern computer language. 
According to the wikipedia definition, a <code>data type</code> is a set of values,
and the allowable operations on those values.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>

<p>
The two fundamental data types in Visual Basic are value types and reference types.
Primitive types (except strings), enumerations, and structures are value types.
Classes, strings, standard modules, interfaces, arrays, and delegates are reference types.
Every type has a default value.
<b>Reference types</b> are created on the Heap. The lifetime of the reference type is
managed by the .NET framework. The default value for reference types is null
reference. Assignment to a variable of a reference type creates a copy of the reference rather
than a copy of the referenced value.
<b>Value types</b> are created on the stack. The lifetime is determined by the
lifetime of the variable. Assignment to a variable of a value type creates a copy of the
value being assigned. Value types have different default values. For example, boolean
default value is False, decimal 0, string an empty string "".
</p>



<h2>Boolean values</h2>

<p>
There is a duality built in our world. There is a Heaven and Earth, water and fire, 
jing and jang, man and woman, love and hatred. In Visual Basic the 
<code>Boolean</code> data type is a primitive data type having one 
of two values: True or False. This is a fundamental data type. Very common 
in computer programs.
</p>

<p>
Happy parents are waiting a child to be born. They have chosen a name for both
possibilities. If it is going to be a boy, they have chosen John. If it is
going to be a girl, they have chosen Jessica. 
</p>

<pre class="code">
Option Strict On

Module Example

    Dim num As Byte
    Dim male As Boolean

    Sub Main()

        Randomize()
        num = CType(Math.Round(Rnd()), Byte)
        
        If num = 0 Then
            male = True
        Else
            male = False
        End If

        If male = True Then
            Console.WriteLine("We will use name John")
        Else
            Console.WriteLine("We will use name Jessica")
        End If

    End Sub

End Module
</pre>

<p>
The program uses a random number generator to simulate our case. 
</p>

<pre class="explanation">
Dim num As Byte
</pre>

<p>
The num variable has a Byte data type. This is important. Byte data
types may have integer values 0..255. 
</p>

<pre class="explanation">
Randomize()
num = CType(Math.Round(Rnd()), Byte)
</pre>

<p>
These two lines pick up randomly 0 or 1. 
The <code>Rnd()</code> function returns a random value 
less than 1, but greater than or equal to zero.  We use the <code>Round()</code> 
method to round the number. 
Random values greater than 0.5 are rounded to 1. All
other random values are rounded to 0. The Double data type is converted into Byte using the
<code>CType()</code> function. So the num variable is assigned 0 or 1.
The <code>Randomize()</code> function initializes a random-number 
generator with a seed based on the system timer.
</p>

<pre class="explanation">
If num = 0 Then
    male = True
Else
    male = False
End If
</pre>

<p>
Depending on the num variable, the Boolean male variable is
set to True or False. 
</p>


<pre class="explanation">
If male = True Then
    Console.WriteLine("We will use name John")
Else
    Console.WriteLine("We will use name Jessica")
End If
</pre>

<p>
If the male variable is set to True, we choose name John.
Otherwise, we choose name Jessica. Control structures like
If/Else statements work with Boolean values. 
</p>


<h2>Integers</h2>

<p>
Integers are a subset of the real numbers. They are written without a fraction or a decimal component. 
Integers fall within a set Z = {..., -2, -1, 0, 1, 2, ...}
Integers are infinite. 
</p>

<p>
In computer languages, integers are primitive data types. Computers can practically work only with a
subset of integer values, because computers have finite capacity. Integers are used to count discrete
entities. We can have 3, 4, 6 humans, but we cannot have 3.33 humans. We can have 3.33 kilograms.
</p>

<table>
<tbody>
<tr>
<th>VB Alias</th>
<th>.NET Type</th>
<th>Size</th>
<th>Range</th>
</tr>
<tr>
<td>SByte</td>
<td>System.SByte</td>
<td>1 byte</td>

<td>-128 to 127</td>
</tr>
<tr class="gray">
<td>Byte</td>
<td>System.Byte</td>
<td>1 byte</td>
<td>0 to 255</td>
</tr>
<tr>
<td>Short</td>
<td>System.Int16</td>

<td>2 bytes</td>
<td>-32,768 to 32,767</td>
</tr>
<tr class="gray">
<td>UShort</td>
<td>System.UInt16</td>
<td>2 bytes</td>
<td>0 to 65,535</td>
</tr>
<tr>
<td>Integer</td>

<td>System.Int32</td>
<td>4 bytes</td>
<td>-2,147,483,648 to 2,147,483,647</td>
</tr>
<tr class="gray">
<td>UInteger</td>
<td>System.UInt32</td>
<td>4 bytes</td>
<td>0 to 4,294,967,295</td>
</tr>

<tr>
<td>Long</td>
<td>System.Int64</td>
<td>8 bytes</td>
<td>-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807</td>
</tr>
<tr class="gray">
<td>ULong</td>
<td>System.UInt64</td>
<td>8 bytes</td>

<td>0 to 18,446,744,073,709,551,615</td>
</tr>
</tbody>
</table>

<p>
These integer types may be used according to our needs. No one, 
(except perhaps for some biblical people), can be older than 120, 130
years. We can then use the Byte type for age variable in our program. 
This will save some memory. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim a As Byte = 254
        
        Console.WriteLine(a)
        a += 1
        Console.WriteLine(a)
        a += 1
        Console.WriteLine(a)

    End Sub

End Module
</pre>

<p>
In this example, we try to assign a value beyond the range
of a data type. Mono compiler gives a System.OverflowException.
The Visual Basic 2008 Express will not compile this example. 
</p>

<hr class="btm">

<p>
Integers can be specified in three different <b>notations</b> in 
Visual Basic. Decimal, hexadecimal and octal.
Octal values are preceded by &amp;o, hexadecimal by &amp;h.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim num1 As Byte = 31
        Dim num2 As Byte = &amp;o31
        Dim num3 As Byte = &amp;h31
        
        Console.WriteLine(num1)
        Console.WriteLine(num2)
        Console.WriteLine(num3)

    End Sub

End Module
</pre>

<p>
We assign 31 to three variables using three notations. And we print them to the console.
</p>

<pre>
$ mono intnotations.exe 
31
25
49
</pre>

<p>
The default notation is the decimal. The program shows these three numbers in decimal. 
</p>

<hr class="btm">

<p>
If we work with integers, we deal with discrete entities. We would use integers to count apples. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Rem number of baskets
        Dim baskets As Byte = 16

        Rem number of apples in each basket 
        Dim apples_in_basket As Byte = 24

        Rem total number of apples
        Dim total As Short = baskets * apples_in_basket

        Console.WriteLine("There are total of {0} apples", total)
        
    End Sub
    
End Module
</pre>


<p>
In our program, we count the total amount of apples. We use the multiplication operation. 
</p>

<pre>
$ mono apples.exe 
There are total of 384 apples
</pre>

<p>
The output of the program. 
</p>

<h2>Floating point numbers</h2>

<p>
Floating point numbers represent real numbers in computing. Real numbers measure continuous quantities. 
Like weight, height or speed. In Visual Basic we have three important floating point types.
Single, Double and Decimal. 
</p>

<table>
<tbody>
<tr>
<th>VB Alias</th>
<th>.NET Type</th>
<th>Size</th>
<th>Precision</th>
<th>Range</th>
</tr>
<tr>
<td>Single</td>
<td>System.Single</td>

<td>4 bytes</td>
<td>7 digits</td>
<td>1.5 x 10<sup>-45</sup> to 3.4 x 10<sup>38</sup></td>
</tr>
<tr class="gray">
<td>Double</td>
<td>System.Double</td>
<td>8 bytes</td>

<td>15-16 digits</td>
<td>5.0 x 10<sup>-324</sup> to 1.7 x 10<sup>308</sup></td>
</tr>
<tr>
<td>Decimal</td>
<td>System.Decimal</td>
<td>16 bytes</td>
<td>28-29 decimal places</td>

<td>1.0 x 10<sup>-28</sup> to 7.9 x 10<sup>28</sup></td>
</tr>
</tbody>
</table>

<p>
The above table gives the characteristics of the floating point types. 
</p>

<p>
We can use various syntax to create floating point values.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim n1 As Single = 1.234
        Dim n2 As Single = 1.2e-3
        Dim n3 As Single = 1 / 3

        Console.WriteLine(n1)
        Console.WriteLine(n2)
        Console.WriteLine(n3)      
      
    End Sub
    
End Module
</pre>

<p>
We have three ways to create floating point values. The first is the 'normal' way using
a decimal point. The second uses scientific notation. And the last one as a result
of a numerical operation. 
</p>

<pre>
$ mono fnotations.exe 
1.234
0.0012
0.3333333
</pre>

<p>
This is the output of the above program. 
</p>

<hr class="btm">

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim n1 As Single = 1 / 3
        Dim n2 As Double = 1 / 3

        If n1 = n2 Then
            Console.WriteLine("Numbers are equal")
        Else 
            Console.WriteLine("Numbers are not equal")
        End If
      
    End Sub
    
End Module
</pre>

<p>
Single and Double values are stored with different precision. 
Caution should be exercised when comparing floating point values. 
</p>

<pre>
$ mono fequal.exe 
Numbers are not equal
</pre>

<p>
And the numbers are not equal. 
</p>

<hr class="btm">

<p>
Let's say a sprinter for 100m ran 9.87s. What is his speed in km/h?
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim distance As Single
        Dim time As Single
        Dim speed As Single
        
        Rem 100m is 0.1 km

        distance = 0.1

        Rem 9.87s is 9.87/60*60 h

        time = 9.87 / 3600

        speed = distance / time

        Console.WriteLine("The average speed of a sprinter is {0} km/h", speed)
       
    End Sub
    
End Module
</pre>

<p>
In this example, it is necessary to use floating point values. 
</p>

<pre class="explanation">
speed = distance / time
</pre>

<p>
To get the speed, we divide the distance by the time. 
</p>


<pre>
$ mono sprinter.exe 
The average speed of a sprinter is 36.47416 km/h
</pre>

<p>
This is the output of the sprinter program. 
</p>

<h2>Enumerations</h2>

<p>
Enumerated type (also called enumeration or enum) 
is a data type consisting of a set of named values.
A variable that has been declared as having an enumerated type can 
be assigned any of the enumerators as a value. Enumerations make
the code more readable. 
</p>

<pre class="code">
Option Strict On

Module Example

    Enum Days
        Monday
        Tuesday
        Wednesday
        Thursday
        Friday
        Saturday
        Sunday
    End Enum


    Sub Main()

        Dim day As Days = Days.Monday
        
        If day = Days.Monday
            Console.WriteLine("It is Monday")
        End If

        Console.WriteLine(day)

    End Sub

End Module
</pre>

<p>
In our code example, we create an enumeration for week days. 
</p>

<pre class="code">
Enum Days
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
    Sunday
End Enum
</pre>

<p>
The enumeration is created with a <code>Enum</code> keyword.
The Monday, Tuesday ... barewords store in fact numbers 0..6. 
</p>

<pre class="explanation">
Dim day As Days = Days.Monday
</pre>

<p>
We have a variable called day, which is of enumerated type Days.
It is initialized to Monday.
</p>

<pre class="explanation">
If day = Days.Monday
    Console.WriteLine("It is Monday")
End If
</pre>

<p>
This code is more readable than if comparing
a day variable to some number. 
</p>


<pre class="explanation">
Console.WriteLine(day)
</pre>

<p>
This line prints 0 to the console. For a computer,
an enum is a number.
</p>

<hr class="btm">

<p>
We further work with enumerations. 
</p>

<pre class="code">
Option Strict On

Module Example

    Enum Seasons As Byte
        Spring = 1
        Summer = 2
        Autumn = 3
        Winter = 4
    End Enum

    Sub Main()

        Dim s1 As Seasons = Seasons.Spring
        Dim s2 As Seasons = Seasons.Autumn
        
        Console.WriteLine(s1)
        Console.WriteLine(s2)

    End Sub

End Module
</pre>

<p>
Seasons can be easily used as enums. We can specify
the underlying type for the enum plus we can give exact
values for them. 
</p>

<pre class="explanation">
Enum Seasons As Byte
    Spring = 1
    Summer = 2
    Autumn = 3
    Winter = 4
End Enum
</pre>

<p>
With the <code>As</code> keyword we specify the
underlying type for the enum. We also give each member a
specific number. 
</p>

<pre class="explanation">
Console.WriteLine(s1)
Console.WriteLine(s2)
</pre>

<p>
These two lines print 1, 3 to the console. 
</p>


<h2>Strings and chars</h2>

<p>
<code>String</code> is a data type representing textual data in computer programs.
A string in Visual Basic is a sequence of Unicode characters. A <code>Char</code>
is a single unicode character. Strings are enclosed by single or double quotes.
</p>

<p>
Since strings are very important in every programming language, we will dedicate a whole chapter to them.
Here we only drop a small example. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim word As String = "ZetCode"

        Dim c As Char = CType(word.SubString(0, 1), Char)

        Console.WriteLine(c)

    End Sub

End Module
</pre>

<p>
The program prints Z character to the terminal. 
</p>

<pre class="explanation">
Dim word As String = "ZetCode"
</pre>

<p>
Here we create a string variable and assign it "ZetCode" value.
</p>

<pre class="explanation">
Dim c As Char = CType(word.SubString(0, 1), Char)
</pre>

<p>
The <code>SubString()</code> method is used to return a
substring from a string. The method return type is a String. We want
to retrieve and assign a single character. This is the reason why we
need to convert a String to a Char with the <code>CType</code> 
function. The character is later printed to the terminal. 
</p>



<h2>Arrays</h2>

<p>
Array is a complex data type which handles a collection of elements. Each of the elements can be
accessed by an index. All the elements of an array must be of the same data type. 
</p>

<p>
We dedicate a whole chapter to arrays, here we show only a small example. 
</p>


<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim array(5) As Integer

        array(0) = 3
        array(1) = 2
        array(2) = 1
        array(3) = 5
        array(4) = 6

        For i As Integer = 0 To array.Length-1
            Console.WriteLine(i)
        Next

    End Sub

End Module
</pre>

<p>
In this example, we declare an array, fill it with data
and then print the contents of the array to the console. 
</p>

<pre class="explanation">
Dim array(5) As Integer
</pre>

<p>
We declare an integer array, which can store up to 5
integers.
</p>

<pre class="explanation">
array(0) = 3
array(1) = 2
array(2) = 1
array(3) = 5
array(4) = 6
</pre>

<p>
Here we assign values to the created array.
</p>

<pre class="explanation">
For i As Integer = 0 To array.Length-1
    Console.WriteLine(i)
Next
</pre>

<p>
We traverse the array and print the data to the
console. The <code>Length</code> property
of the array gives us the length of the array in question.
</p>


<h2>Date</h2>

<p>
A <code>Date</code> is value type, which contain date values, 
time values, or date and time values.
</p>


<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim today As Date

        today = Now()

        System.Console.WriteLine(today)
        System.Console.WriteLine(today.ToShortDateString())
        System.Console.WriteLine(today.ToShortTimeString())

    End Sub

End Module
</pre>

<p>
We show today's date in three different formats. Date &amp; time, 
date and time. 
</p>

<pre class="explanation">
Dim today As Date
</pre>

<p>
We declare a variable of <code>Date</code> datatype. 
</p>

<pre class="explanation">
today = Now()
</pre>

<p>
Returns the current date and time, uses the computer's system date and time.
</p>

<pre class="explanation">
System.Console.WriteLine(today)
</pre>

<p>
This line prints the date in full format. 
</p>

<pre class="explanation">
System.Console.WriteLine(today.ToShortDateString())
System.Console.WriteLine(today.ToShortTimeString())
</pre>

<p>
The <code>ToShortDateString()</code>
returns a short date string format, the <code>ToShortTimeString()</code>
returns a short time string format. 
</p>

<pre>
$ mono date.exe 
8/17/2010 1:19:05 PM
8/17/2010
1:19 PM
</pre>

<p>
The output of the example.
</p>


<h2>Type casting</h2>

<p>
We often work with multiple data types at once. Converting one data 
type to another one is a common job in programming. <b>Type conversion</b> or 
<b>typecasting</b> refers to changing an entity of one data type into another.
There are two types of conversion. Implicit and explicit. Implicit type 
conversion, also known as coercion, is an automatic type conversion by the compiler. 
</p>

<pre class="code">
Rem Option Strict On

Module Example

    Sub Main()

        Dim val As Byte

        val = 0.54

        Console.WriteLine(val)
        Console.WriteLine(12 + 12.5)
        Console.WriteLine("12" + 12) 
        Console.WriteLine("12" &amp; 12)

    End Sub
    
End Module
</pre>

<p>
In this example, we have an bunch of implicit conversions. 
</p>

<pre class="explanation">
Rem Option Strict On
</pre>

<p>
Some of the implicit conversions are not possible when the
Option Strict statement is On. This is why we comment this line.
</p>

<pre class="explanation">
val = 0.54
</pre>

<p>
A floating point value is assigned to the variable of a
<code>Byte</code> data type. It is an integer
data type. The value is rounded to 1; some precision is lost.
This is a <b>narrowing</b> implicit conversion.
</p>

<pre class="explanation">
Console.WriteLine(12 + 12.5)
</pre>

<p>
We add two values. One integer and one floating point value.
The result is a floating point value. It is a <b>widening</b> implicit conversion.
</p>

<pre class="explanation">
Console.WriteLine("12" + 12) 
</pre>

<p>
The result is 24. The string is implicitly converted to a number.
</p>

<pre class="explanation">
Console.WriteLine("12" &amp; 12)
</pre>

<p>
The result is 1212. An integer is converted to a string and
the two strings are added. 
</p>

<hr class="btm">

<p>
Next we will show some explicit conversions in Visual Basic.
</p>

<table>
<thead>
<tr>
<th>Function</th><th>Converts to</th> 
</tr>
</thead>
<tbody>
<tr>
<td>CBool</td><td>Boolean</td>
</tr>
<tr class="gray">
<td>CByte</td><td>Byte</td>
</tr>
<tr>
<td>CChar</td><td>Unicode character</td>
</tr>
<tr class="gray">
<td>CDate</td><td>Date</td>
</tr>
<tr>
<td>CDb1</td><td>Double</td>
</tr>
<tr class="gray">
<td>CDec</td><td>Decimal</td>
</tr>
<tr>
<td>Clnt</td><td>Integer</td>
</tr>
<tr class="gray">
<td>CLng</td><td>Long</td>
</tr>
<tr>
<td>CObj</td><td>Object</td>
</tr>
<tr class="gray">
<td>CShort</td><td>Short</td>
</tr>
<tr>
<td>CSng</td><td>Single</td>
</tr>
<tr class="gray">
<td>CStr</td><td>String</td>
</tr>
</tbody>
</table>

<p>
We have several functions to perform explicit conversions. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Console.WriteLine(CByte(0.4))
        Console.WriteLine(CByte(0.9))

        Console.WriteLine(CShort(12 + 12.5))

        Console.WriteLine(Val("1071 Fifth Avenue"))

    End Sub
    
End Module
</pre>

<p>

</p>

<pre class="explanation">
Console.WriteLine(CByte(0.4))
Console.WriteLine(CByte(0.9))
</pre>

<p>
These two lines perform a narrowing explicit conversion.
The first number is rounded to 0, the second to 1. 
</p>

<pre class="explanation">
Console.WriteLine(Val("1071 Fifth Avenue"))
</pre>

<p>
The <code>Val()</code> function returns the numbers 
contained in a string. In our case, 1071.
</p>

<pre>
$ mono explicit.exe 
0
1
24
1071
</pre>

<p>
Output of the example. 
</p>

<p>
In this part of the Visual Basic tutorial, we covered data types and
their conversions.  
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified August 17, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

